import sys
import traceback

from PyQt5.QtCore import pyqtSlot, pyqtSignal, QRunnable, QObject
import serial


class WorkerSignals(QObject):
    result = pyqtSignal(object)
    error = pyqtSignal(tuple)


class Action(QRunnable):
    def __init__(self, ser: serial.Serial, cmd):
        super(Action, self).__init__()

        self.signals = WorkerSignals()
        self.ser = ser
        self.cmd = cmd

    @pyqtSlot()
    def run(self):
        try:
            # print("run1")
            self.ser.flushInput()
            self.ser.write(self.cmd)
            # print("run2")
            ret = self.ser.readline()
            # print("run3 ret = {}".format(ret))
        except:
            # print("except")
            traceback.print_exc()
            exctype, value = sys.exc_info()[:2]
            self.signals.error.emit((exctype, value, traceback.format_exc()))
        else:
            # print(ret)
            self.signals.result.emit(ret)  # Return the result of the processing
        # finally:
        #     self.signals.finished.emit()  # Done
